<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import { useRoute } from "vue-router";
import { invoke } from "@tauri-apps/api/core";
import { debug } from "@tauri-apps/plugin-log";

const route = useRoute();

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 根据后端定义调整接口
interface Company {
    id: number;
    name: string;
    type_id: number; // 公司类型: 1-材料生产单位，2-供应商，3-其他服务型
    status: number; // 公司状态: 1-正常，2-停业，3-注销
    address: string;
    contacts: string[]; // 联系人信息数组
    staff_num: number; // 员工数量
    capacity: string; // 能够生产什么材料
    remark: string;
    created_by: string;
    modified_by: string;
    created_at: string;
    modified_at: string;
}

const isDisable = ref(true);
const loading = ref(false);
const error = ref("");
const success = ref("");

const company = ref<Company>(createEmptyCompany());
const companies = ref<Company[]>([]);

// 公司类型选项
const companyTypes = [
    { value: 1, label: "材料生产单位" },
    { value: 2, label: "供应商" },
    { value: 3, label: "其他服务型" },
];

// 公司状态选项
const companyStatuses = [
    { value: 1, label: "正常" },
    { value: 2, label: "停业" },
    { value: 3, label: "注销" },
];

// 获取公司ID
const companyId = computed(() => {
    return route.params.id ? parseInt(route.params.id as string) : null;
});

// 创建空公司对象
function createEmptyCompany(): Company {
    return {
        id: 0,
        name: "",
        type_id: 1,
        status: 1,
        staff_num: 1, //至少1个人
        address: "",
        capacity: "",
        remark: "",
        contacts: [],
        created_by: "",
        modified_by: "",
        created_at: "",
        modified_at: "",
    };
}

// 获取公司详情
async function fetchCompanyDetail() {
    if (!companyId.value) return;

    loading.value = true;
    error.value = "";

    try {
        const response: ApiResponse<Company> = await invoke("company_detail", {
            company_id: companyId.value, // 注意：API参数名是material_id，但实际应该是公司id
        });

        if (response.status_code === 200 && response.data) {
            company.value = response.data;
            success.value = "公司详情加载成功";
        } else {
            error.value = response.message || "获取公司详情失败";
        }
    } catch (err) {
        error.value = "网络请求失败";
        console.error("获取公司详情失败:", err);
    } finally {
        loading.value = false;
    }
}

// 创建或更新公司
async function saveCompany() {
    if (!company.value.name?.trim()) {
        error.value = "公司名称不能为空";
        return;
    }

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
        let response: ApiResponse<Company>;

        if (company.value.id === 0) {
            // 创建公司
            response = await invoke("create_company", {
                data: JSON.stringify(company.value),
            });
        } else {
            // 更新公司
            response = await invoke("update_company", {
                data: JSON.stringify(company.value),
            });
        }

        debug(`company: ${JSON.stringify(company.value)}`);

        if (response.status_code === 200 && response.data) {
            company.value = response.data;
            success.value =
                company.value.id === 0 ? "公司创建成功" : "公司更新成功";
            isDisable.value = true;

            // 如果是创建公司，更新URL
            if (company.value.id !== 0 && !companyId.value) {
                window.history.replaceState(
                    {},
                    "",
                    `/company/${company.value.id}`,
                );
            }
        } else {
            error.value = response.message || "保存公司失败";
        }
    } catch (err) {
        error.value = "网络请求失败";
        console.error("保存公司失败:", err);
    } finally {
        loading.value = false;
    }
}

// 编辑公司
function editCompany() {
    isDisable.value = false;
}

// 取消编辑
function cancelEdit() {
    isDisable.value = true;
    if (companyId.value) {
        fetchCompanyDetail();
    } else {
        company.value = createEmptyCompany();
    }
    error.value = "";
    success.value = "";
}

// 获取公司类型标签
function getCompanyTypeLabel(typeId: number): string {
    const type = companyTypes.find((t) => t.value === typeId);
    return type ? type.label : "未知类型";
}

// 获取公司状态标签
function getCompanyStatusLabel(status: number): string {
    const statusObj = companyStatuses.find((s) => s.value === status);
    return statusObj ? statusObj.label : "未知状态";
}

// 添加联系人
function addContact() {
    if (!company.value.contacts) {
        company.value.contacts = [];
    }
    company.value.contacts.push("");
}

// 更新联系人
function updateContact(index: number, value: string) {
    if (company.value.contacts) {
        company.value.contacts[index] = value;
    }
}

// 删除联系人
function removeContact(index: number) {
    if (company.value.contacts) {
        company.value.contacts.splice(index, 1);
    }
}

// 页面加载时初始化
onMounted(() => {
    if (companyId.value) {
        fetchCompanyDetail();
    } else {
        // 新建公司时默认为编辑模式
        isDisable.value = false;
    }
});

// 监听路由变化
watch(
    () => route.params.id,
    (newId) => {
        if (newId) {
            fetchCompanyDetail();
        } else {
            company.value = createEmptyCompany();
            isDisable.value = false;
        }
    },
);
</script>

<template>
    <main>
        <div class="container w-full h-full relative p-6 max-w-6xl mx-auto">
            <!-- 页面标题 -->
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold">
                    {{
                        isDisable
                            ? "公司详情"
                            : company.id === 0
                              ? "创建公司"
                              : "编辑公司"
                    }}
                </h1>
                <div class="flex gap-2" v-if="isDisable && company.id !== 0">
                    <button @click="editCompany" class="btn btn-primary btn-sm">
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="m14.304 4.844 2.852 2.852M7 7H4a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-4.5m2.409-9.91a2.017 2.017 0 0 1 0 2.853l-6.844 6.844L8 14l.713-3.565 6.844-6.844a2.015 2.015 0 0 1 2.852 0Z"
                            />
                        </svg>
                        编辑
                    </button>
                </div>
            </div>

            <!-- 消息提示 -->
            <div v-if="error" class="alert alert-error mb-6">
                <svg
                    class="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <span>{{ error }}</span>
            </div>

            <div v-if="success" class="alert alert-success mb-6">
                <svg
                    class="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <span>{{ success }}</span>
            </div>

            <!-- 加载状态 -->
            <div v-if="loading" class="text-center p-8">
                <span class="loading loading-spinner loading-lg"></span>
                <p class="mt-2">加载中...</p>
            </div>

            <div v-else>
                <!-- 基本信息区域 -->
                <div
                    class="bg-base-100 rounded-lg border border-base-300 p-6 mb-6"
                >
                    <h3
                        class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b border-base-300"
                    >
                        基本信息
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- 公司名称 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >公司名称</span
                                >
                            </label>
                            <input
                                v-model="company.name"
                                type="text"
                                placeholder="公司名称"
                                class="input input-bordered w-full"
                                :disabled="isDisable"
                            />
                        </div>

                        <!-- 员工数量 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >员工数量</span
                                >
                            </label>
                            <input
                                v-model.number="company.staff_num"
                                type="number"
                                placeholder="员工数量"
                                class="input input-bordered w-full"
                                :disabled="isDisable"
                            />
                        </div>

                        <!-- 公司类型 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >公司类型</span
                                >
                            </label>
                            <select
                                v-model="company.type_id"
                                class="select select-bordered w-full"
                                :disabled="isDisable"
                            >
                                <option
                                    v-for="type in companyTypes"
                                    :key="type.value"
                                    :value="type.value"
                                >
                                    {{ type.label }}
                                </option>
                            </select>
                        </div>

                        <!-- 公司状态 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >公司状态</span
                                >
                            </label>
                            <select
                                v-model="company.status"
                                class="select select-bordered w-full"
                                :disabled="isDisable"
                            >
                                <option
                                    v-for="status in companyStatuses"
                                    :key="status.value"
                                    :value="status.value"
                                >
                                    {{ status.label }}
                                </option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- 联系信息区域 -->
                <div
                    class="bg-base-100 rounded-lg border border-base-300 p-6 mb-6"
                >
                    <h3
                        class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b border-base-300"
                    >
                        联系信息
                    </h3>
                    <div class="grid grid-cols-1 gap-4">
                        <!-- 公司地址 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >公司地址</span
                                >
                            </label>
                            <input
                                v-model="company.address"
                                type="text"
                                placeholder="公司地址"
                                class="input input-bordered w-full"
                                :disabled="isDisable"
                            />
                        </div>

                        <!-- 联系人信息 -->
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >联系人信息</span
                                >
                                <span class="label-text-alt text-gray-500"
                                    >格式: 姓名:电话,邮箱</span
                                >
                            </label>
                            <div class="space-y-2">
                                <div
                                    v-for="(contact, index) in company.contacts"
                                    :key="index"
                                    class="flex items-center gap-2"
                                >
                                    <input
                                        :value="contact"
                                        @input="
                                            updateContact(
                                                index,
                                                (
                                                    $event.target as HTMLInputElement
                                                ).value,
                                            )
                                        "
                                        type="text"
                                        placeholder="例如: 张三:13800138000,zhangsan@example.com"
                                        class="input input-bordered flex-1"
                                        :disabled="isDisable"
                                    />
                                    <button
                                        v-if="!isDisable"
                                        class="btn btn-ghost btn-xs text-error"
                                        @click="removeContact(index)"
                                        type="button"
                                    >
                                        <svg
                                            class="w-4 h-4"
                                            fill="none"
                                            stroke="currentColor"
                                            viewBox="0 0 24 24"
                                        >
                                            <path
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                d="M6 18L18 6M6 6l12 12"
                                            />
                                        </svg>
                                    </button>
                                </div>
                                <button
                                    v-if="!isDisable"
                                    class="btn btn-outline btn-sm w-full"
                                    @click="addContact"
                                    type="button"
                                >
                                    <svg
                                        class="w-4 h-4"
                                        fill="none"
                                        stroke="currentColor"
                                        viewBox="0 0 24 24"
                                    >
                                        <path
                                            stroke-linecap="round"
                                            stroke-linejoin="round"
                                            stroke-width="2"
                                            d="M12 6v6m0 0v6m0-6h6m-6 0H6"
                                        />
                                    </svg>
                                    添加联系人
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 生产能力区域 -->
                <div
                    class="bg-base-100 rounded-lg border border-base-300 p-6 mb-6"
                >
                    <h3
                        class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b border-base-300"
                    >
                        生产能力
                    </h3>
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >生产能力描述</span
                            >
                        </label>
                        <textarea
                            v-model="company.capacity"
                            placeholder="描述公司能够生产或提供的材料、产品和服务..."
                            class="textarea textarea-bordered h-24 w-full"
                            :disabled="isDisable"
                        ></textarea>
                    </div>
                </div>

                <!-- 备注信息区域 -->
                <div
                    class="bg-base-100 rounded-lg border border-base-300 p-6 mb-6"
                >
                    <h3
                        class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b border-base-300"
                    >
                        备注信息
                    </h3>
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">公司备注</span>
                        </label>
                        <textarea
                            v-model="company.remark"
                            placeholder="公司备注，可以输入公司特点，例如：公司规模、行业背景、地理位置，服务质量，响应速度等等。"
                            class="textarea textarea-bordered h-32 w-full"
                            :disabled="isDisable"
                        ></textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-center gap-4 mt-6 pb-6" v-if="!loading">
            <button
                class="btn btn-primary"
                @click="saveCompany"
                v-if="!isDisable"
                :disabled="loading"
            >
                <span
                    v-if="loading"
                    class="loading loading-spinner loading-sm"
                ></span>
                <svg
                    class="w-5 h-5"
                    aria-hidden="true"
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    fill="none"
                    viewBox="0 0 24 24"
                    v-else
                >
                    <path
                        stroke="currentColor"
                        stroke-linecap="round"
                        stroke-width="2"
                        d="M11 16h2m6.707-9.293-2.414-2.414A1 1 0 0 0 16.586 4H5a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1V7.414a1 1 0 0 0-.293-.707ZM16 20v-6a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v6h8ZM9 4h6v3a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1V4Z"
                    />
                </svg>
                {{ company.id === 0 ? "创建公司" : "保存" }}
            </button>
            <button
                class="btn btn-outline"
                @click="cancelEdit"
                v-if="!isDisable"
                :disabled="loading"
            >
                取消
            </button>
            <button
                class="btn btn-primary"
                @click="editCompany"
                v-if="isDisable && company.id !== 0"
            >
                <svg
                    class="w-5 h-5"
                    aria-hidden="true"
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    fill="none"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke="currentColor"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M10.779 17.779 4.36 19.918 6.5 13.5m4.279 4.279 8.364-8.643a3.027 3.027 0 0 0-2.14-5.165 3.03 3.03 0 0 0-2.14.886L6.5 13.5m4.279 4.279L6.499 13.5m2.14 2.14 6.213-6.504M12.75 7.04 17 11.28"
                    />
                </svg>
                编辑
            </button>
        </div>
    </main>
</template>

<style scoped>
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}
</style>
